package com.gree.rpc.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.gree.commom.result.BaseResult;
import com.gree.commom.utils.JsonUtil;
import com.gree.rpc.entity.Admin;
import com.gree.rpc.service.CartService;
import com.gree.rpc.vo.CartResult;
import com.gree.rpc.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(interfaceClass = CartService.class,timeout = 120000)
@Component
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Value("${user.cart}")
    private String userCart;

    /**
     * 加入购物车
     * @param cartVo
     * @param admin
     * @return
     */
    @Override
    public BaseResult addCart(CartVo cartVo, Admin admin) throws Exception {
        //未登录,用户信息未存在
        if(admin == null || admin.getAdminId() == null){
            return  BaseResult.error();
        }
        Integer id = admin.getAdminId();
        //获取当前用户的购物车信息
        HashOperations<String,String,String> ops = redisTemplate.opsForHash();
        Map<String, String> cartMap = ops.entries(userCart + ":" + id);
        //如果购物车信息不为空，修改购物车信息
        if(!CollectionUtils.isEmpty(cartMap)){
            //根据商品id获取商品信息
            String cartStr = cartMap.get(String.valueOf(cartVo.getGoodsId()));
            if(!StringUtils.isEmpty(cartStr)){
                //如果商品存在,修改商品信息
                CartVo cart= JsonUtil.jsonStr2Object(cartStr, CartVo.class);
                //修改商品数量
                cart.setGoodsNum(cart.getGoodsNum() + cartVo.getGoodsNum());
                //修改商品最新的价格
                cart.setMarketPrice(cartVo.getMarketPrice());
                cartMap.put(String.valueOf(cart.getGoodsId()),JsonUtil.object2JsonStr(cart));
            }else {
                //如果商品不存在,新增购物车信息
                cartMap.put(String.valueOf(cartVo.getGoodsId()),JsonUtil.object2JsonStr(cartVo));
            }
        }else {
            //如果购物车为空，新增购物信息
            cartMap = new HashMap<>();
            cartMap.put(String.valueOf(cartVo.getGoodsId()),JsonUtil.object2JsonStr(cartVo));
        }
        ops.putAll(userCart+":"+id,cartMap);
        return BaseResult.success();
    }

    /**
     * 获取购物车数量
     * @param admin
     * @return
     */
    @Override
    public Integer getCartNum(Admin admin) throws Exception {
        //未登录
        if(admin == null || admin.getAdminId() == null){
            return  0;
        }
        HashOperations<String,String,String> ops = redisTemplate.opsForHash();
        Map<String, String> cartMap = ops.entries(userCart + ":" + admin.getAdminId());
        //如果购物车信息不为空
        Integer result = 0;
        if(!CollectionUtils.isEmpty(cartMap)){
            for (Map.Entry<String, String> entry : cartMap.entrySet()) {
                CartVo cartVo = JsonUtil.jsonStr2Object(entry.getValue(), CartVo.class);
                result+=cartVo.getGoodsNum();
            }
        }
        return result;
    }

    /**
     * 获取购物车列表
     * @param admin
     * @return
     */
    @Override
    public CartResult getCartList(Admin admin) {
        if(admin == null || admin.getAdminId() == null){
            return null;
        }
        CartResult cartResult =null;
        List<CartVo> cartList = new ArrayList<>();
        HashOperations<String,String,String> ops = redisTemplate.opsForHash();
        Map<String, String> cartMap = ops.entries(userCart + ":" + admin.getAdminId());
        if(!CollectionUtils.isEmpty(cartMap)){
            cartResult = new CartResult();
            List<CartVo> cartVoList = cartMap.values().stream().map(e -> JsonUtil.jsonStr2Object(e, CartVo.class)).collect(Collectors.toList());
            //总价
            BigDecimal totalPrice = cartList.stream().map(e -> e.getMarketPrice().multiply(new BigDecimal(String.valueOf(e.getGoodsNum())))).reduce(BigDecimal.ZERO, BigDecimal::add);
            //保留小数点后两位,四舍五入
            totalPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
            cartResult.setCartList(cartVoList);
            cartResult.setTotalPrice(totalPrice);
        }
     return cartResult;
    }

    /**
     * 清除购物车信息
     * @param admin
     * @return
     */
    @Override
    public BaseResult clearCart(Admin admin) {
        if(admin == null || admin.getAdminId() == null){
            return null;
        }
        //获取购物车信息
        HashOperations<String,String,String> ops = redisTemplate.opsForHash();
        Map<String, String> cartMap = ops.entries(userCart + ":" + admin.getAdminId());
        if(CollectionUtils.isEmpty(cartMap)){
            return BaseResult.error();
        }else {
            redisTemplate.delete(userCart+":"+admin.getAdminId());
        }
        return BaseResult.success();
    }
}
